<template>
  <div>
    <el-card class="box-card">
      <el-button type="primary" @click="showDialogByAdd">添加品牌</el-button>
      <el-table
        :data="trademarkList"
        border
        style="width: 100%; margin: 20px 0"
      >
        <el-table-column
          type="index"
          align="center"
          prop="date"
          label="序号"
          width="60"
        />
        <el-table-column
          align="center"
          prop="tmName"
          label="品牌名称"
          width="150"
        />
        <el-table-column prop="address" label="品牌LOGO">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" alt="" style="width: 100px">
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template v-slot="{row}">
            <el-button type="warning" class="el-icon-edit" @click="editOneTrademark(row.id)">修改</el-button>
            <el-button type="danger" class="el-icon-delete" @click="delOneTrademark(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="limit"
        align="center"
        layout="prev, pager, next, jumper, -> ,sizes,total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      title="添加品牌"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form ref="tmForm" :model="tmForm" :rules="rules">
        <el-form-item label="品牌名称" label-width="90px" prop="tmName">
          <el-input v-model="tmForm.tmName" style="width: 400px" />
        </el-form-item>
        <el-form-item label="品牌Logo" label-width="90px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept=".jpg,.jpeg,.png"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过3M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateOneTrademark">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqUpdateOneTrademark, reqGetTrademarkList, reqGetOneTrademark, reqAddOneTrademark, reqDelOneTrademark } from '@/api/product/trademark'
export default {
  name: 'Trademark',
  data() {
    return {
      trademarkList: [], // 品牌信息列表
      currentPage: 1, // 当前页
      limit: 5, // 每页多少条
      total: 0, // 总共多少条
      dialogVisible: false,
      imageUrl: '',
      tmForm: {
        tmName: '',
        logoUrl: ''
      },
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        logoUrl: [{ required: true, message: '请选择一张图片', trigger: 'change' }]
      }
    }
  },
  mounted() {
    // 发送请求获取品牌信息
    this.getTrademarkList()
  },
  methods: {
    // 7.点击添加按钮弹出遮罩层
    showDialogByAdd() {
      this.dialogVisible = true
      this.tmForm.tmName = ''
      this.imageUrl = ''
      this.tmForm.id = ''
    },
    // 6.点击修改数据回显
    async editOneTrademark(id) {
      const res = await reqGetOneTrademark(id)
      if (res.code === 200) {
        this.tmForm = res.data
        this.imageUrl = res.data.logoUrl
        this.dialogVisible = true
      }
    },
    // 5.删除一个品牌信息
    delOneTrademark(id) {
      this.$confirm('你真的要删除此条数据吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await reqDelOneTrademark(id)
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getTrademarkList()
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 4.添加或更新一个品牌
    addOrUpdateOneTrademark() {
      this.$refs['tmForm'].validate(async(valid) => {
        if (valid) {
          let res
          if (this.tmForm.id) {
            res = await reqUpdateOneTrademark(this.tmForm)
          } else {
            res = await reqAddOneTrademark(this.tmForm)
          }
          if (res.code === 200) {
            this.dialogVisible = false
            this.$message.success(`${this.tmForm.id ? '更新' : '添加'}成功`)
            this.getTrademarkList()
          } else {
            this.$message.error(res.message)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 3.图片上传相关方法
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.tmForm.logoUrl = res.data
      this.$refs['tmForm'].clearValidate(['logoUrl'])
    },
    beforeAvatarUpload(file) {
      const imageArr = ['image/jpg', 'image/jpeg', 'image/png']
      const isJPG = imageArr.includes(file.type)
      const isLt3M = file.size / 1024 / 1024 < 3

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt3M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }
      return isJPG && isLt3M
    },
    // 2.分页相关方法
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.limit = val
      this.getTrademarkList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getTrademarkList()
    },
    // 1.获取品牌信息列表
    async getTrademarkList() {
      const { currentPage: page, limit } = this
      const res = await reqGetTrademarkList(page, limit)
      // console.log(res)
      if (res.code === 200) {
        this.trademarkList = res.data.records
        this.total = res.data.total
      } else {
        this.$message.error('获取商品数据失败...')
      }
    }
  }
}
</script>

<style></style>
